<?php
// +----------------------------------------------------------------------
// | CoreThink [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.thinkphp.cn/ All rights reserved.
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
namespace app\attachment\controller;

use app\common\controller\Base;
use util\Logger;

/**
 * 腾讯云对象上传
 * @author nagi
 */
class TencentUpload extends Base
{
    private $bucket;
    private $cosClient;

    public function __construct($driver)
    {
        try {
            $this->cosClient = new \Qcloud\Cos\Client(array(
                'region'      => $driver['endpoint'], #存储桶地域，如ap-guangzhou,ap-beijing-1
                'credentials' => array(
                    'secretId'  => $driver['accessKey'],     //"云 API 密钥 SecretId";
                    'secretKey' => $driver['secretKey'],    //"云 API 密钥 SecretKey";
                ),
            ));
            $this->bucket    = $driver['bucket'];  //存储桶名称 格式：BucketName-APPID
        } catch (\Exception $e) {
            trace($e->getMessage(), 'error');
        }
    }

    /**
     * 上传
     * @param null $info
     * @return array
     */
    public function upload($info = null)
    {
        if (empty($info)) {
            $info = $this->dealFiles($_FILES);
            $info = $info['file'];
        }

        // 要上传文件的本地路径
        $filepath = $info['tmp_name'];

        //文件名
        $object = $info['md5'] . '.' . $info['ext'];
//        $object = $info['name'];
        //存储目录
		$path = 'w3/tuike/oline/images/' . date('Ymd', time());
        $key  = $path . '/' . $object;

        //putObject(上传接口，最大支持上传5G文件)
        //Upload(高级上传接口，默认使用分块上传最大支持50T)
        try {
            $this->cosClient->putObject(array(
                'Bucket' => $this->bucket,
                'Key'    => $key,
                'Body'   => fopen($filepath, 'rb')
            ));
            $result = ['code' => 0, 'msg' => '上传成功', 'name' => $object, 'url' => $key];
        } catch (\Exception $e) {
            trace($e, 'error');
            $result = ['code' => -1, 'msg' => '上传失败', 'data' => null];
        }

        return $result;
    }

    /**
     * 上传本地文件
     * @param string $filename 文件名
     * @param string $filepath 文件目录
     * @param string $file 本地文件
     * @return string
     * @throws \Exception
     */
    public function upload_local(string $filename, string $filepath, string $file)
    {
        try {
            //文件名
            $object = $filename;
            $type   = mime_content_type($file);
            //存储目录
            if (str_starts_with($type, 'image/')) {
                $path = 'images/' . $filepath;
            } elseif (str_starts_with($type, 'video/')) {
                $path = 'videos/' . $filepath;
            } else {
                $path = $filepath;
            }
            //上传文件
            $oss_file = $path . '/' . $object;
            $this->cosClient->putObject(array(
                'Bucket' => $this->bucket,
                'Key'    => $oss_file,
                'Body'   => fopen($file, 'rb')
            ));
            return $oss_file;
        } catch (\Exception $e) {
            Logger::error('上传失败：' . $e->getMessage());
            throw new \Exception('上传失败');
        }
    }


    /**
     * 删除文件
     * @param string $object 对象名
     * @param string $driver 上传驱动
     * @return array
     */
    public function delete($object = '', $driver = '')
    {
        if (empty($object)) {
            $object = $this->request->param('object');
        }
        try {
            $this->cosClient->deleteObject(array(
                'Bucket' => $this->bucket,
                'Key'    => $object,
            ));

            deleteModel('attachment', ['path' => $object, 'driver' => $driver]);
            $result = ['code' => 0, 'msg' => '删除成功'];
        } catch (\Exception $e) {
            trace($err, 'error');
            $result = ['code' => -1, 'msg' => '删除失败'];
        }
        return $result;
    }

    /**
     * 转换上传文件数组变量为正确的方式
     * @access private
     * @param array $files 上传的文件变量
     * @return array
     */
    private function dealFiles($files)
    {
        $fileArray = array();
        $n         = 0;
        foreach ($files as $key => $file) {
            if (is_array($file['name'])) {
                $keys  = array_keys($file);
                $count = count($file['name']);
                for ($i = 0; $i < $count; $i++) {
                    $fileArray[$n]['key'] = $key;
                    foreach ($keys as $_key) {
                        $fileArray[$n][$_key] = $file[$_key][$i];
                    }
                    $n++;
                }
            } else {
                $fileArray = $files;
                break;
            }
        }
        return $fileArray;
    }

}
